package com.work.yshop.mvp.presenter;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.work.yshop.model.CartItem;
import com.work.yshop.model.Favorite;
import com.work.yshop.model.Order;
import com.work.yshop.model.Product;
import com.work.yshop.model.ProductHistory;
import com.work.yshop.mvp.contract.UserDataContract;
import com.work.yshop.mvp.model.UserDataModel;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 用户数据Presenter
 * 实现UserDataContract.Presenter接口，连接View和Model
 */
public class UserDataPresenter implements UserDataContract.Presenter {

    private static final String TAG = "UserDataPresenter";
    private WeakReference<UserDataContract.View> viewRef;
    private UserDataModel model;
    
    public UserDataPresenter(Context context) {
        this.model = new UserDataModel(context);
    }
    
    @Override
    public void attachView(UserDataContract.View view) {
        viewRef = new WeakReference<>(view);
    }
    
    @Override
    public void detachView() {
        if (viewRef != null) {
            viewRef.clear();
            viewRef = null;
        }
    }
    
    /**
     * 获取当前绑定的View
     */
    private UserDataContract.View getView() {
        return viewRef != null ? viewRef.get() : null;
    }
    
    /**
     * 添加到购物车并立即购买
     * @param product 商品
     * @param quantity 数量
     * @param callback 回调
     */
    @Override
    public void addToCartAndBuy(Product product, int quantity, UserDataContract.BuyCallback callback) {
        new AsyncTask<Object, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Object... objects) {
                Product product = (Product) objects[0];
                int quantity = (int) objects[1];
                return model.addToCart(product, quantity);
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                if (success) {
                    if (callback != null) {
                        callback.onAddSuccess(product.getId());
                    }
                } else {
                    if (callback != null) {
                        callback.onAddFailed("添加到购物车失败");
                    }
                }
            }
        }.execute(product, quantity);
    }
    
    @Override
    public void addHistory(Product product) {
        new AsyncTask<Product, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Product... products) {
                return model.addHistory(products[0]);
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null && success) {
                    view.showResult(true, "已添加到浏览历史");
                }
            }
        }.execute(product);
    }
    
    @Override
    public void loadHistoryList() {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        view.showLoading();
        
        new AsyncTask<Void, Void, List<ProductHistory>>() {
            @Override
            protected List<ProductHistory> doInBackground(Void... voids) {
                return model.getHistoryList();
            }
            
            @Override
            protected void onPostExecute(List<ProductHistory> historyList) {
                UserDataContract.View view = getView();
                if (view != null) {
                    view.hideLoading();
                    
                    if (historyList.isEmpty()) {
                        view.showEmptyView(0); // 0表示历史记录
                    } else {
                        view.showHistoryList(historyList);
                    }
                }
            }
        }.execute();
    }
    
    @Override
    public void clearHistory() {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... voids) {
                return model.clearHistory();
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null) {
                    if (success) {
                        view.showResult(true, "已清空浏览历史");
                        view.showEmptyView(0); // 0表示历史记录
                    } else {
                        view.showResult(false, "清空浏览历史失败");
                    }
                }
            }
        }.execute();
    }
    
    @Override
    public void addFavorite(Product product) {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        new AsyncTask<Product, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Product... products) {
                return model.addFavorite(products[0]);
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null) {
                    if (success) {
                        view.showResult(true, "已添加到收藏");
                    } else {
                        view.showResult(false, "添加收藏失败");
                    }
                }
            }
        }.execute(product);
    }
    
    @Override
    public void removeFavorite(int productId) {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        new AsyncTask<Integer, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Integer... integers) {
                return model.removeFavorite(integers[0]);
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null) {
                    if (success) {
                        view.showResult(true, "已取消收藏");
                    } else {
                        view.showResult(false, "取消收藏失败");
                    }
                }
            }
        }.execute(productId);
    }
    
    @Override
    public void checkFavoriteStatus(int productId, UserDataContract.FavoriteCallback callback) {
        new AsyncTask<Integer, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Integer... integers) {
                return model.isFavorite(integers[0]);
            }
            
            @Override
            protected void onPostExecute(Boolean isFavorite) {
                if (callback != null) {
                    callback.onResult(isFavorite);
                }
            }
        }.execute(productId);
    }
    
    @Override
    public void loadFavoriteList() {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        view.showLoading();
        
        new AsyncTask<Void, Void, List<Favorite>>() {
            @Override
            protected List<Favorite> doInBackground(Void... voids) {
                return model.getFavoriteList();
            }
            
            @Override
            protected void onPostExecute(List<Favorite> favoriteList) {
                UserDataContract.View view = getView();
                if (view != null) {
                    view.hideLoading();
                    
                    if (favoriteList.isEmpty()) {
                        view.showEmptyView(1); // 1表示收藏
                    } else {
                        view.showFavoriteList(favoriteList);
                    }
                }
            }
        }.execute();
    }
    
    @Override
    public void addToCart(Product product, int quantity) {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        new AsyncTask<Object, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Object... objects) {
                Product product = (Product) objects[0];
                int quantity = (int) objects[1];
                return model.addToCart(product, quantity);
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null) {
                    if (success) {
                        view.showResult(true, "已添加到购物车");
                    } else {
                        view.showResult(false, "添加到购物车失败");
                    }
                }
            }
        }.execute(product, quantity);
    }
    
    @Override
    public void updateCartItemQuantity(int productId, int quantity) {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        new AsyncTask<Object, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Object... objects) {
                int productId = (int) objects[0];
                int quantity = (int) objects[1];
                return model.updateCartItemQuantity(productId, quantity);
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null) {
                    if (success) {
                        // 更新成功后重新加载购物车数据
                        loadCartItems();
                    } else {
                        view.showResult(false, "更新购物车失败");
                    }
                }
            }
        }.execute(productId, quantity);
    }
    
    @Override
    public void removeCartItem(int productId) {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        new AsyncTask<Integer, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Integer... integers) {
                return model.removeCartItem(integers[0]);
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null) {
                    if (success) {
                        view.showResult(true, "已从购物车移除");
                        // 移除成功后重新加载购物车数据
                        loadCartItems();
                    } else {
                        view.showResult(false, "从购物车移除失败");
                    }
                }
            }
        }.execute(productId);
    }
    
    @Override
    public void loadCartItems() {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        view.showLoading();
        
        new AsyncTask<Void, Void, List<CartItem>>() {
            @Override
            protected List<CartItem> doInBackground(Void... voids) {
                return model.getCartItems();
            }
            
            @Override
            protected void onPostExecute(List<CartItem> cartItems) {
                UserDataContract.View view = getView();
                if (view != null) {
                    view.hideLoading();
                    
                    if (cartItems.isEmpty()) {
                        view.showEmptyView(2); // 2表示购物车
                    } else {
                        view.showCartItems(cartItems);
                    }
                }
            }
        }.execute();
    }
    
    @Override
    public void clearCart() {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... voids) {
                return model.clearCart();
            }
            
            @Override
            protected void onPostExecute(Boolean success) {
                UserDataContract.View view = getView();
                if (view != null) {
                    if (success) {
                        view.showResult(true, "已清空购物车");
                        view.showEmptyView(2); // 2表示购物车
                    } else {
                        view.showResult(false, "清空购物车失败");
                    }
                }
            }
        }.execute();
    }
    
    @Override
    public void createOrder(UserDataContract.OrderCallback callback) {
        new AsyncTask<Void, Void, Order>() {
            private String errorMessage;
            
            @Override
            protected Order doInBackground(Void... voids) {
                try {
                    return model.createOrder();
                } catch (Exception e) {
                    errorMessage = e.getMessage();
                    return null;
                }
            }
            
            @Override
            protected void onPostExecute(Order order) {
                if (order != null) {
                    if (callback != null) {
                        callback.onSuccess(order);
                    }
                } else {
                    if (callback != null) {
                        callback.onError(errorMessage != null ? errorMessage : "创建订单失败");
                    }
                }
            }
        }.execute();
    }
    
    @Override
    public void createSelectedOrder(List<CartItem> selectedItems, UserDataContract.OrderCallback callback) {
        new AsyncTask<List<CartItem>, Void, Order>() {
            private String errorMessage;
            
            @Override
            protected Order doInBackground(List<CartItem>... lists) {
                try {
                    List<CartItem> items = lists[0];
                    return model.createSelectedOrder(items);
                } catch (Exception e) {
                    errorMessage = e.getMessage();
                    Log.e(TAG, "创建订单失败", e);
                    return null;
                }
            }
            
            @Override
            protected void onPostExecute(Order order) {
                if (order != null) {
                    if (callback != null) {
                        callback.onSuccess(order);
                    }
                } else {
                    if (callback != null) {
                        callback.onError(errorMessage != null ? errorMessage : "创建订单失败");
                    }
                }
            }
        }.execute(selectedItems);
    }
    
    @Override
    public void loadOrderList() {
        UserDataContract.View view = getView();
        if (view == null) return;
        
        view.showLoading();
        
        new AsyncTask<Void, Void, List<Order>>() {
            @Override
            protected List<Order> doInBackground(Void... voids) {
                return model.getOrderList();
            }
            
            @Override
            protected void onPostExecute(List<Order> orderList) {
                UserDataContract.View view = getView();
                if (view != null) {
                    view.hideLoading();
                    
                    if (orderList.isEmpty()) {
                        view.showEmptyView(3); // 3表示订单
                    } else {
                        view.showOrderList(orderList);
                    }
                }
            }
        }.execute();
    }
    
    @Override
    public void saveDirectOrder(Order order, UserDataContract.OrderCallback callback) {
        UserDataContract.View view = getView();
        
        new AsyncTask<Order, Void, Order>() {
            private String errorMessage;
            
            @Override
            protected Order doInBackground(Order... orders) {
                try {
                    return model.saveDirectOrder(orders[0]);
                } catch (Exception e) {
                    errorMessage = e.getMessage();
                    return null;
                }
            }
            
            @Override
            protected void onPostExecute(Order result) {
                if (result != null) {
                    // 创建订单成功
                    if (callback != null) {
                        callback.onSuccess(result);
                    }
                    
                    if (view != null) {
                        view.showResult(true, "订单创建成功");
                    }
                } else {
                    // 创建订单失败
                    String message = errorMessage != null ? errorMessage : "创建订单失败";
                    
                    if (callback != null) {
                        callback.onError(message);
                    }
                    
                    if (view != null) {
                        view.showResult(false, message);
                    }
                }
            }
        }.execute(order);
    }
} 